package netbayServlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import netbay.NetbayUtility;
import netbay.TransactionManager;

/**
 * Servlet implementation class ViewServlet
 */
@WebServlet("/ViewServlet")
public class ViewServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ViewServlet() {
		super();
	}

	public void init() {
		String configPath = getServletContext().getRealPath(
				"/WEB-INF/config.properties");
		NetbayUtility.init(configPath);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		TransactionManager tm = new TransactionManager();

		String mode = request.getParameter("criteria");

		System.out.println(mode);

		List result = null;

		if (mode.equalsIgnoreCase("ConversationId")) {

			String conver = request.getParameter("conversationId");
			result = tm.getDisplayConversationId(conver);

		}

		else {

			String from = request.getParameter("fromTime");
			String to = request.getParameter("toTime");

			System.out.println("from : " + from + " - to : " + to);

			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");

			Date fromDate = new Date();
			Date toDate = new Date();

			try {
				fromDate = sdf.parse(from);
			} catch (ParseException e) {
				fromDate = null;
			}

			try {
				toDate = sdf.parse(to);
			} catch (ParseException e) {
				toDate = null;
			}

			System.out.println("from : " + fromDate + " - to : " + toDate);

			if (mode.equalsIgnoreCase("recvTCDtime")) {

				result = tm.getDisplayTransactionLogRecvTcd(fromDate, toDate);

			} else if (mode.equalsIgnoreCase("recvJPMCtime")) {

				result = tm.getDisplayTransactionLogRecvJpmc(fromDate, toDate);

			}

		}

		request.setAttribute("result", result);

		RequestDispatcher rd = getServletContext().getRequestDispatcher(
				"/TrackViewer.jsp");
		rd.forward(request, response);

	}
}
